<?php
require_once "metadata/City.class.php";
class CityModel
{
    var $db;

    function __construct($db_link)
    {
        $this->db = $db_link;
    }

    function getAllCitiesInCountry($id)
    {
        $query = "SELECT * FROM city WHERE countryid = '$id'" or die("Error in the consult.." . mysqli_error($this->db));

        //execute the query.
        $result = $this->db->query($query);

        $cities = array();

        while($row = mysqli_fetch_array($result))
        {

            $city = new City($row["id"], $row["name"], $row["population"], $row["countryid"]);

            $cities[count($cities)] = $city;
        }
        return $cities;
    }

    function addCity($city)
    {
        $query = "INSERT INTO city (id, name, population, countryid) VALUES ('$city->id', '$city->name', $city->population, '$city->country')" or die("Error in the consult.." . mysqli_error($this->db));


        mysqli_query($this->db, $query)or die("Error in the consult.." . mysqli_error($this->db));

        return 200;
    }

    function deleteCity($cityID)
    {
        $query = "DELETE FROM city WHERE id = '$cityID'" or die("Error in the consult.." . mysqli_error($this->db));


        mysqli_query($this->db, $query) or die("Error in the consult.." . mysqli_error($this->db));

        return 200;
    }

    function getCityName($city_id)
    {
        $query = "SELECT * FROM city WHERE id = '$city_id'" or die("Error in the consult.." . mysqli_error($this->db));

        //execute the query.
        $result = $this->db->query($query);

        while($row = mysqli_fetch_array($result))
        {
            $city = new City($row["id"], $row["name"], $row["population"], $row["countryid"]);
            return $city;
        }
    }

    function updateCity($city)
    {

        $query = "UPDATE city SET name = '$city->name', population = $city->population, countryid = '$city->country' WHERE id = '$city->id' " or die("Error in the consult.." . mysqli_error($this->db));

        //execute the query.
        $result = $this->db->query($query) or die("Error in the consult.." . mysqli_error($this->db));

        return 200;
    }
}
?>